package com.wlyuan.open.application.listener;

import com.alibaba.excel.util.StringUtils;
import com.wlyuan.core.domain.event.DomainEventListener;
import com.wlyuan.open.domain.api.service.OpenApiInfoLogService;
import com.wlyuan.open.domain.client.OpenClient;
import com.wlyuan.open.domain.client.OpenClientBind;
import com.wlyuan.open.domain.client.event.ClientBindEvent;
import com.wlyuan.open.domain.client.respository.OpenClientBindRepository;
import com.wlyuan.open.domain.qrcode.service.QrCodeService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import lombok.var;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.springframework.stereotype.Service;

import java.util.Optional;

/**
 * @author lijing
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class ClientBindEventListener implements DomainEventListener<ClientBindEvent> {
    private final OpenClientBindRepository openClientBindRepository;
    private final QrCodeService qrCodeService;
    private final OpenApiInfoLogService openApiInfoLogService;

    @Override
    @Subscribe(sticky = true, threadMode = ThreadMode.ASYNC)
    public void handle(ClientBindEvent event) {
        logger.info("client绑定账号完成通知");
        Optional.ofNullable(event.getOpenClient()).ifPresent(openClient -> {
            var bind = new OpenClientBind(openClient.getTenantId().getId(), openClient.getMobile());
            //绑定记录
            openClientBindRepository.save(bind);
            //删除授权接口
            openApiInfoLogService.save(event.getOpenClient().getId(), Optional.ofNullable(event.getAfterClient()).map(OpenClient::getId).orElse(null));
        });
        //删除二维码文件
        if (StringUtils.isNotBlank(event.getQrCodeId())) {
            //扫描二维码
            qrCodeService.scanner(event.getQrCodeId());
            //删除OSS文件
            qrCodeService.remove(event.getQrCodeId());
        }
    }
}
